package com.jshcbd.modules.asset.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshcbd.framework.poi.excel.def.NormalExcelConstants;
import com.jshcbd.framework.poi.excel.entity.ExportParams;
import com.jshcbd.framework.poi.excel.view.EntityExcelView;
import com.jshcbd.framework.vo.LoginUser;
import com.jshcbd.framework.vo.Result;
import com.jshcbd.framework.query.QueryGenerator;
import com.jshcbd.modules.asset.dto.InventoryItemDto;
import com.jshcbd.modules.asset.entity.InventoryEntity;
import com.jshcbd.modules.asset.entity.InventoryItemEntity;
import com.jshcbd.modules.asset.service.IInventoryService;
import com.jshcbd.modules.asset.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zhoucd
 * @date
 * @description
 */
@Slf4j
@Api(tags="盘点管理")
@RestController
@RequestMapping("/inventory")
public class InventoryController {
    @Autowired
    private IInventoryService iInventoryService;


    @ApiOperation("盘点记录")
    @RequestMapping(value ={"/list","/list/{state}"} , method = RequestMethod.GET)
    public Result<IPage<InventoryVo>> queryPageList(InventoryVo inventoryVo,
                                                    @PathVariable(required = false) Integer state,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<InventoryVo>> result = new Result();
        QueryWrapper<InventoryVo> queryWrapper = QueryGenerator.initQueryWrapper(inventoryVo, req.getParameterMap());
        queryWrapper.orderByDesc("state");
        queryWrapper.orderByDesc("start_date");
        queryWrapper.orderByDesc("end_date");
        if(state !=null){
            queryWrapper.eq("state",state);
        }
        Page<InventoryVo> page = new Page(pageNo, pageSize);
        IPage<InventoryVo> pageList = iInventoryService.pageView(page, queryWrapper);
        result.setSuccess(true);
        result.setData(pageList);
        log.info(pageList.toString());
        return result;
    }


    @ApiOperation("新增盘点记录")
    @PostMapping("/add")
    public Result add(@RequestBody InventoryEntity inventoryEntity) {
        try {
            inventoryEntity.setState(2);
            iInventoryService.doSave(inventoryEntity);
            return Result.ok("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }


    @ApiOperation("盘点资产明细")
    @GetMapping(value = {"/itemsByMainId/{mainId}","/itemsByMainId/{mainId}/{state}"})
    public Result<IPage<InventoryItemVo>> itemsByMainId(InventoryItemDto dto,@PathVariable  String mainId,
                                                        @PathVariable(required = false)  Integer state,
                                                        @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<InventoryItemVo>> result = new Result();
        Page<InventoryItemVo> page = new Page(pageNo, pageSize);

        QueryWrapper queryWrapper = QueryGenerator.initQueryWrapper(dto, req.getParameterMap());
        queryWrapper.eq("main_id",mainId);
        if(state != null){
            queryWrapper.eq("item_state",state);
        }
        IPage<InventoryItemVo> pageList = iInventoryService.itemPageView(page, queryWrapper);
        result.setSuccess(true);
        result.setData(pageList);
        log.info(pageList.toString());
        return result;
    }


    @ApiOperation("修改盘点记录状态")
    @PutMapping("/updateItemAssetState")
    public Result updateItemAssetState(@RequestBody InventoryItemDto inventoryItemDto) {
        try {

            InventoryItemEntity entity =  iInventoryService.getItemById(inventoryItemDto.getId());
            entity.setUseState(inventoryItemDto.getUseState());
            entity.setItemState(inventoryItemDto.getItemState());
            entity.setInventoryPhoto(inventoryItemDto.getInventoryPhoto());
            iInventoryService.updateItem(entity);
            iInventoryService.updateAssetItemState(inventoryItemDto);
            return Result.ok("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @ApiOperation("结束盘点")
    @PutMapping("/end/{id}")
    public Result end(@PathVariable String id) {
        try {
            iInventoryService.doInventoryEnd(id);
            return Result.ok("操作成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }



    @ApiOperation("盘点进度")
    @GetMapping("/progress/{mainId}")
    public Result<InventoryProgressVo> progress(@PathVariable String mainId) {
        Result<InventoryProgressVo> result = new Result();
        InventoryProgressVo vo = iInventoryService.getProgress(mainId);
        result.setData(vo);
        return result;
    }


    @ApiOperation("根据标签进行资产盘点")
    @GetMapping("/doInventory/{mainId}/{addressId}/{rfid}")
    public Result<InventoryItemVo> doInventory(@PathVariable String mainId,@PathVariable String addressId,@PathVariable String rfid) {
        Result<InventoryItemVo> result = new Result();
        InventoryItemVo vo = iInventoryService.doInventory(mainId,addressId,rfid);
        result.setData(vo);
        return result;
    }




    @ApiOperation("导出盘点明细")
    @GetMapping("/exprotXls/{mainId}")
    public ModelAndView exprotExcel(InventoryItemDto dto,
                                           @PathVariable  String mainId,
                                           HttpServletRequest req,
                                           HttpServletResponse res) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();



        QueryWrapper queryWrapper = QueryGenerator.initQueryWrapper(dto, req.getParameterMap());
        queryWrapper.eq("main_id",mainId);
        List<InventoryItemVo> dataList  =  iInventoryService.itemView(queryWrapper);
        String title = "资产折旧";
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, InventoryItemVo.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("资产盘点结果", title));
        mv.addObject(NormalExcelConstants.DATA_LIST, dataList);
        return mv;
    }


}



